package com.lvm.app.controller;


import cn.hutool.core.util.StrUtil;
import com.alibaba.druid.util.StringUtils;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.lvm.app.api.entity.LvmFileRec;
import com.lvm.app.api.entity.LvmKeyRec;
import com.lvm.app.api.entity.LvmTopicClassify;
import com.lvm.app.api.entity.LvmTopicRec;
import com.lvm.app.dao.LvmKeyRecMapper;
import com.lvm.app.dao.LvmTopicClassifyMapper;
import com.lvm.app.dao.LvmTopicRecMapper;
import com.lvm.app.exception.BusinessException;
import com.lvm.app.service.LvmKeyRecService;
import com.lvm.app.task.VideoTask;
import com.lvm.app.task.VideoTaskHolder;
import com.lvm.app.util.R;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 主题内容记录 前端控制器
 * </p>
 *
 * @author zhouxf
 * @since 2021-03-01
 */
@RestController
@RequestMapping("/topic")
@Api(tags = "文章主题")
public class LvmTopicRecController {
    @Autowired
    LvmTopicRecMapper lvmTopicRecMapper;
    @Autowired
    LvmKeyRecMapper lvmKeyRecMapper;
    @Autowired
    private LvmTopicClassifyMapper lvmTopicClassifyMapper;
    @Autowired
    LvmKeyRecService lvmKeyRecService;

    @GetMapping("/queryTopicList")
    public R<IPage<LvmTopicRec>> queryTopicList(Page page, String keys, String title, Integer status,Long classifyId){
        List<String> temp = null;
        if(StrUtil.isNotBlank(keys)){
           temp = new ArrayList<>(Arrays.asList(keys.split(",")));
        }
        IPage<LvmTopicRec> recores = lvmTopicRecMapper.queryTopic(page,temp,title,status,classifyId);
        recores.setRecords(recores.getRecords().stream().map((item)->{
            item.setPicListObj(JSONObject.parseArray(item.getPicList(), LvmFileRec.class));
            item.setVideoListObj(JSONObject.parseArray(item.getVideoList(), LvmFileRec.class));
            item.setThumbListObj(JSONObject.parseArray(item.getThumbList(), LvmFileRec.class));
            item.setCoverPicObj(JSONObject.parseObject(item.getCoverPic(), LvmFileRec.class));
            item.setKeyListObj(JSONObject.parseArray(item.getKeyList(),String.class));
            return item;
        }).collect(Collectors.toList()));
        return R.ok(recores);
    }

    @GetMapping("/queryTopicDetail")
    public R<LvmTopicRec> queryTopicDetail(Long id){
        LvmTopicRec res  = lvmTopicRecMapper.selectById(id);
        res.setVideoListObj(JSONObject.parseArray(res.getVideoList(), LvmFileRec.class));
        res.setThumbListObj(JSONObject.parseArray(res.getThumbList(), LvmFileRec.class));
        res.setCoverPicObj(JSONObject.parseObject(res.getCoverPic(), LvmFileRec.class));
        res.setKeyListObj(JSONObject.parseArray(res.getKeyList(),String.class));
        res.setPicListObj(JSONObject.parseArray(res.getPicList(),LvmFileRec.class));
        return R.ok(res);
    }

    @PostMapping("/updateTopic")
    public R updateTopic(@RequestBody  LvmTopicRec rec){
            if(rec.getKeyListObj()!=null&&rec.getKeyListObj().size()>0){
                rec.setKeyList(JSONObject.toJSONString(new HashSet<>(rec.getKeyListObj())));
            }else {
                rec.setKeyList("");
            }
            rec.setVideoList(JSONObject.toJSONString(rec.getVideoListObj()));
            rec.setPicList(JSONObject.toJSONString(rec.getPicListObj()));
            rec.setCoverPic(JSONObject.toJSONString(rec.getCoverPicObj()));
            Set<String> videoKey = new HashSet<>(rec.getKeyListObj());
            for(String key:videoKey){
                    List<LvmKeyRec> hisKeys = lvmKeyRecMapper.selectList(Wrappers.<LvmKeyRec>lambdaQuery().eq(LvmKeyRec::getKeyVal,key));
                    if(hisKeys.size()>0){
                        for(LvmKeyRec his:hisKeys){
                            List<String> relKeys = JSONObject.parseArray(his.getRelKeys(),String.class);
                            his.setNumber(his.getNumber()+1);
                            relKeys.addAll(rec.getKeyListObj());
                            Set<String> keySet = new HashSet<String>();
                            keySet.addAll(relKeys);
                            his.setRelKeys(JSON.toJSONString(keySet));
                            lvmKeyRecMapper.updateById(his);
                        }
                    }else{
                        LvmKeyRec newKey = new LvmKeyRec();
                        newKey.setKeyVal(key);
                        newKey.setNumber(1l);
                        newKey.setRelKeys(JSON.toJSONString(videoKey));
                        lvmKeyRecMapper.insert(newKey);
                    }
            }
            lvmTopicRecMapper.updateById(rec);
            return R.ok();
    }

    @PostMapping("/addKey")
    public R<LvmKeyRec> addKey(@RequestBody LvmKeyRec rec){
        lvmKeyRecService.saveOrUpdate(rec);
        return R.ok(rec);
    }
    @GetMapping("/queryKey")
    public R<IPage<LvmKeyRec>> queryKey(Page page,String key){
        if(page==null){
            page =new Page();
            page.setSize(20);
            page.setCurrent(1);
        }
        IPage<LvmKeyRec> res = lvmKeyRecMapper.queryKey(page,key);
        return R.ok(res);
    }
    @GetMapping("/queryClassify")
    @ApiOperation("检索分类")
    public R<List<Map<String,Object>>> queryClassify(String classify){
        List<Map<String,Object>> classifyListRes= new ArrayList<>();
        List<LvmTopicClassify> classifyList = lvmTopicClassifyMapper.selectList(Wrappers.lambdaQuery());
        List<LvmTopicClassify> parentList = classifyList.stream().filter((item)->{
            return !(item.getParentId()!=null&&item.getParentId()>0);
        }).collect(Collectors.toList());
        classifyListRes = parentList.stream().map((item)->{
            Map<String,Object> c= new HashMap<>();
            c.put("id",item.getId());
            c.put("value",item.getId());
            c.put("label",item.getClassify());
            c.put("classify",item.getClassify());
            c.put("createTime",item.getCreateTime());
            c.put("children",classifyList.stream().filter((w)->{
                return w.getParentId()!=null&&w.getParentId().equals(item.getId());
            }).map((k)->{
                Map<String,Object> c2= new HashMap<>();
                c2.put("children",new ArrayList<>());
                c2.put("id",k.getId());
                c2.put("value",k.getId());
                c2.put("label",k.getClassify());
                c2.put("classify",k.getClassify());
                c2.put("parentId",k.getParentId());
                c2.put("createTime",k.getCreateTime());
                return c2;
            }).collect(Collectors.toList()));
            return c;
        }).collect(Collectors.toList());

        return R.ok(classifyListRes);
    }

    @GetMapping("/deleteClassIfy")
    @ApiOperation("删除分类")
    public R deleteClassIfy(Long id){
        LvmTopicClassify hisClassify = lvmTopicClassifyMapper.selectById(id);
        if(hisClassify.getNumber()>0){
            return R.failed("这个分类无法删除");
        }else{
            lvmTopicClassifyMapper.deleteById(id);
        }
        return R.ok();
    }

    @PostMapping("/addClassify")
    @ApiOperation("添加分类")
    public R addClassify(@RequestBody LvmTopicClassify classify){
        LvmTopicClassify hisClassify = lvmTopicClassifyMapper.selectOne(Wrappers.<LvmTopicClassify>lambdaQuery().eq(LvmTopicClassify::getClassify,classify.getClassify()));
        if(hisClassify!=null){
            throw new BusinessException("已经存在这个分类无法添加");
        }
        classify.setNumber(0);
        lvmTopicClassifyMapper.insert(classify);
        return R.ok();
    }
    @PostMapping("/updateClassify")
    @ApiOperation("更新分类")
    public R updateClassify(@RequestBody LvmTopicClassify classify){
        LvmTopicClassify hisClassify = lvmTopicClassifyMapper.selectById(classify.getId());
        hisClassify.setClassify(classify.getClassify());
        lvmTopicClassifyMapper.updateById(hisClassify);
        return R.ok();
    }


}
